package com.spingweb.controller;

import com.spingweb.util.CommonResult;
import com.spingweb.util.PageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * create by yongli on 2021-05-12 10:44
 * 函数有返回值的类型约束
 */
@ControllerAdvice
public class GlobalErrorHandlerController {

    private static final Logger logger = LoggerFactory.getLogger(GlobalErrorHandlerController.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult restError(Exception e) throws PageException {


        logger.info("enter in  restError");
        RequestAttributes attr = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attr).getRequest();
        String url = request.getRequestURI();
        if (url != null && url.contains("rest")) {
            return CommonResult.failure(e.getMessage());
        }
        throw new PageException(e.getMessage());
    }

    @ExceptionHandler(PageException.class)
    public String pageError(Exception e) {
        logger.info("enter in page error");
        return "error";
    }
}
